package com.doghome.news.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import com.doghome.news.utils.SftpUtil;
import com.jcraft.jsch.SftpException;

@RestController
public class FileUploadController {
	
	/**
	 * 使用wangEditor控件
	 * response返回数据格式
	 * 成功
	 * {
		    "errno": 0, // 注意：值是数字，不能是字符串
		    "data": {
		        "url": "xxx", // 图片 src ，必须
		        "alt": "yyy", // 图片描述文字，非必须
		        "href": "zzz" // 图片的链接，非必须
		    }
		}
	 * 失败
	 * {
		    "errno": 1, // 只要不等于 0 就行
		    "message": "失败信息"
		}
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public Map<String,Object> upload(@RequestPart("uploadFile") MultipartFile file){
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		String fileName = file.getOriginalFilename();
		String newFileName = UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
		boolean success = false;
		SftpUtil sftp = new SftpUtil("sheep", "80124431", "localhost", 22);
        //登录
        sftp.login();
        //输出到服务器特定目录
        try {
			sftp.upload("/home/sheep/mywork/file-server/news-system", newFileName, file.getInputStream());
			success = true;
		} catch (SftpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
        //退出
        sftp.logout();  
        if(success) {
        	result.put("errno", 0);
        	data.put("url", "http://localhost:3030/news-system/"+newFileName);
        	data.put("alt", newFileName);
        	result.put("data", data);
        }else {
        	result.put("errno", 1);
        	result.put("message", "文件上传失败");
        }
		return result;
	}

}
